<template>
  <Dialog :text="text" v-model:show="show" @submit="submit">
    <template v-slot:content>
      <ImageUpload @submit="uploadImage" :default-src="goods.base64code" />

      <div class="property">

	<span>价格: </span>
	<input type="number" v-model.number="price"/>

	<span>类别: </span>
	<select v-model="selected">
	  <template v-for="(option, index) in goodsTypes" :key="index">
	    <option :value="option.name">{{option.name}}</option>
	  </template>
	</select>

	<span>名称: </span>
	<input type="text" v-model="name"/>

	<span>库存: </span>
	<input type="number" v-model.number="stock"/>

	<span>介绍: </span>
	<textarea v-model="introduction"/>

      </div>

    </template>
  </Dialog>
</template>

<script lang="ts" setup>
 import { GoodsService, GoodsTypeService, ImageUploadService } from '@/service'
 import { inject, onMounted, PropType, provide, Ref, ref } from '@vue/runtime-core'
 import Dialog from './Dialog.vue'
 import ImageUpload from './ImageUpload.vue'
 
 const props = defineProps({
   text: String,
   goods: Object as PropType<Goods>
 })

 const name = ref(props.goods!.name)
 const price = ref(props.goods!.price)
 const stock = ref(props.goods!.stock)
 const type = ref(props.goods!.type)
 const introduction = ref(props.goods!.introduction)
 
 const goodsTypes = ref<Array<GoodsType>>([])
 const selected = ref(props.goods!.type)
 const show = ref(false)

 const shouldUpdate = inject<boolean>('shouldUpdate') 
 let imageFile: File | null = null

 function uploadImage(file: File) {
   imageFile = file
   console.log(file)
 }

 async function submit() {
   // use insert one
   // TODO how to upload image ?

   await ImageUploadService.upload(imageFile == null ? dataURLtoFile(props.goods!.base64code, props.goods!.src) : imageFile)
   await GoodsService.updateOne({
     id: props.goods?.id!,
     name: name.value,
     price: price.value,
     stock: stock.value,
     type: selected.value,
     introduction: introduction.value,
     src: imageFile == null ? props.goods!.src : imageFile!.name
   })

   shouldUpdate.value = true
 }

 function dataURLtoFile(dataurl: string, filename: string) {
   let arr = dataurl.split(',')
   let mime = arr[0].match(/:(.*?);/)![1]
   let bstr = atob(arr[1])
   let n = bstr.length
   let u8arr = new Uint8Array(n)
   
   while(n--){
     u8arr[n] = bstr.charCodeAt(n);
   }
   
   return new File([u8arr], filename, {type:mime});
 }

 onMounted(async () => {
   goodsTypes.value = await GoodsTypeService.findAll()
 })
</script>

<style lang="scss" scoped>
 div.property {
   display: grid;
   grid-template-columns: repeat(2, 100px);
 }

 label {
   display: block;
   margin-left: auto;
   margin-right: auto;
   width: 50%;
   span {
     width: 20%;
     float: left;
     text-align: right;
   }

   input {
     outline: 0;
     background: #f2f2f2;
     width: 70%;
     border: 0;
     margin: 0 0 15px;
     padding: 15px;
     box-sizing: border-box;
     font-size: 14px;
   }

 }
</style>